package com.horoscope.astrology.zodiac.signs.free.activity

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.recyclerview.widget.GridLayoutManager
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.adapter.CompatibilityAdapter
import com.horoscope.astrology.zodiac.signs.free.bean.ConstellationBean
import com.horoscope.astrology.zodiac.signs.free.infc.OnItemClickedListener
import com.horoscope.astrology.zodiac.signs.free.utils.*
import kotlinx.android.synthetic.main.activity_compatibility.*
import kotlinx.android.synthetic.main.item_header_compatibility.*
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT as WRAP_CONTENT1


class CompatibilityActivity : BaseActivity() {

    private lateinit var mAdapter: CompatibilityAdapter
    private var backTitle = ""
    private lateinit var layoutManager: GridLayoutManager
    private var mDataList: ArrayList<ConstellationBean>? = null
    private var left = true
    private var right = false
    private var isMove = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_compatibility)
        StatusBarUtil.setColor(this, "#0AFFFFFF")

        // 选择框常转
        MyAnimationUtils.startRotation(image_view_you_select)
        MyAnimationUtils.startRotation(image_view_partner_select)

        if (intent?.getStringExtra(TYPE_FROM) == TYPE_LOVE) {
            backTitle = getString(R.string.label_love_compatibility)
            // 爱情选星座页面
            FlurryEventUtil.putDataToEvent(EventType.TYPE_LOVE_COMPATIBILITY_SHOW, null, null)
        } else {
            // 星座匹配选星座页面
            FlurryEventUtil.putDataToEvent(EventType.TYPE_ZODIAC_COMPATIBILITY_SHOW, null, null)
            backTitle = getString(R.string.label_zodiac_compatibility)
        }
        initTitleBar(
            this@CompatibilityActivity,
            R.id.btn_back_edit_name,
            R.id.text_view_back_title,
            backTitle
        )
        initRecycler()
        okClick()

    }

    private fun okClick() {
        text_view_ok_compatibility?.setOnClickListener {
            if (text_view_h1.text.isNotEmpty() && text_view_h2.text.isNotEmpty()) {
                when (intent?.getStringExtra(TYPE_FROM)) {
                    TYPE_LOVE -> {
                        // 选星座页面点击了 ok
                        FlurryEventUtil.putDataToEvent(
                            EventType.TYPE_LOVE_COMPATIBILITY_CONTINUE,
                            null,
                            null
                        )
                        startActivity(
                            LoveResultActivity.generateIntent(
                                this,
                                text_view_h1.text.toString(), text_view_h2.text.toString()
                            )
                        )
                    }
                    TYPE_ZODIAC -> {
                        // 星座匹配选星座页面点击了 ok
                        FlurryEventUtil.putDataToEvent(
                            EventType.TYPE_ZODIAC_COMPATIBILITY_CONTINUE,
                            null,
                            null
                        )
                        startActivity(
                            ZodiacResultActivity.generateIntent(
                                this,
                                text_view_h1.text.toString(), text_view_h2.text.toString()
                            )
                        )
                    }
                }
            }
        }
        image_view_you.setOnClickListener {
            left = true
            right = false
            image_view_you_select.visibility = View.VISIBLE
            image_view_partner_select.visibility = View.INVISIBLE
        }
        image_view_partner.setOnClickListener {
            left = false
            right = true
            image_view_partner_select.visibility = View.VISIBLE
            image_view_you_select.visibility = View.INVISIBLE
        }
    }

    private fun initRecycler() {
        mRecyclerView = findViewById(R.id.recycler_view_compatibility)
        mAdapter = CompatibilityAdapter(this)
        layoutManager = GridLayoutManager(this, 3)
        // 顶部两个对比 和 其它的星座图
        mDataList = ConstellationUtil.getConstellationList()
        mAdapter.setData(mDataList!!)
        mRecyclerView.layoutManager = layoutManager
        // 边距RecyclerView里设置了paddingEnd
        mRecyclerView.addItemDecoration(CharacterDecoration(13f, 13f))
        mRecyclerView.adapter = mAdapter
        mAdapter.setOnItemClickedListener(object : OnItemClickedListener {
            override fun onItemClick(view: View, position: Int, string: String) {
                mDataList!!.forEach {
                    it.select = it.name == mDataList!![position].name
                }

                //如果点击的时候，之前动画还没结束，那么就让点击事件无效
                if (isMove) {
                    return
                }

                val itemView: ImageView = view.findViewById(R.id.iv_item_title_icon)
                val img: ImageView = getView(itemView)
                val startLocation = IntArray(2)
                itemView.getLocationInWindow(startLocation)

                if (image_view_you.drawable != null && image_view_partner.drawable != null) {
                    if (left) {
                        isMoveImage(
                            img, image_view_you, startLocation,
                            ConstellationUtil.getIconByName(mDataList!![position].name)
                        )
                        image_view_you_select.visibility = View.VISIBLE
                        image_view_partner_select.visibility = View.INVISIBLE
                        text_view_h1.text = mDataList!![position].name
                    } else if (right) {
                        isMoveImage(
                            img, image_view_partner, startLocation,
                            ConstellationUtil.getIconByName(mDataList!![position].name)
                        )
                        image_view_partner_select.visibility = View.VISIBLE
                        image_view_you_select.visibility = View.INVISIBLE
                        text_view_h2.text = mDataList!![position].name
                    }
                } else if (left && !right && image_view_partner.drawable == null) {   // 左有 右无
                    if (image_view_partner.drawable == null) {
                        left = false
                        right = true
                    } else {
                        left = true
                        right = false
                    }
                    isMoveImage(
                        img, image_view_you, startLocation,
                        ConstellationUtil.getIconByName(mDataList!![position].name)
                    )
                    image_view_you_select.visibility = View.INVISIBLE
                    image_view_partner_select.visibility = View.VISIBLE
                    text_view_h1.text = mDataList!![position].name
                } else if (!left && right && image_view_you.drawable == null) {
                    if (image_view_partner.drawable == null) {
                        left = true
                        right = false
                    } else {
                        left = false
                        right = true
                    }
                    isMoveImage(
                        img, image_view_partner, startLocation,
                        ConstellationUtil.getIconByName(mDataList!![position].name)
                    )
                    image_view_partner_select.visibility = View.INVISIBLE
                    image_view_you_select.visibility = View.VISIBLE
                    text_view_h2.text = mDataList!![position].name
                } else if (!left && right && image_view_partner.drawable == null) {
                    if (image_view_you.drawable == null) {
                        left = true
                        right = false
                    } else {
                        left = false
                        right = true
                    }
                    isMoveImage(
                        img, image_view_partner, startLocation,
                        ConstellationUtil.getIconByName(mDataList!![position].name)
                    )
                    image_view_partner_select.visibility = View.VISIBLE
                    image_view_you_select.visibility = View.INVISIBLE
                    text_view_h2.text = mDataList!![position].name
                } else if (left && !right && image_view_you.drawable == null) {
                    isMoveImage(
                        img, image_view_you, startLocation,
                        ConstellationUtil.getIconByName(mDataList!![position].name)
                    )
                    image_view_you_select.visibility = View.VISIBLE
                    image_view_partner_select.visibility = View.INVISIBLE
                    text_view_h1.text = mDataList!![position].name
                }
                buttonIsEnable()
            }
        })
    }

    private fun isMoveImage(img: ImageView, img1: ImageView, startLocation: IntArray, id: Int) {
        Handler().postDelayed({
            try {
                val endLocation = IntArray(2)
                // 获取终点的坐标
                img1.getLocationInWindow(endLocation)
                moveAnim(img, startLocation, endLocation)
                img1.setImageResource(id)
                ObjectAnimator.ofFloat(img1, "alpha", 0f, 1f)
                    .setDuration(1000)
                    .start()
            } catch (localException: Exception) {
            }
        }, 50L)
    }

    companion object {
        const val TYPE_FROM = "from"
        const val TYPE_LOVE = "love"
        const val TYPE_ZODIAC = "zodiac"
        fun generateIntent(context: Context, from: String): Intent {
            val intent = Intent(context, CompatibilityActivity::class.java)
            intent.putExtra(TYPE_FROM, from)
            return intent
        }
    }

    // 根据星座选择情况，判断按钮的状态
    override fun onResume() {
        super.onResume()
        buttonIsEnable()
    }

    private fun buttonIsEnable() {
        if (text_view_h1.text.isNullOrEmpty() || text_view_h2.text.isNullOrEmpty()) {
            text_view_ok_compatibility.isClickable = false
            text_view_ok_compatibility.alpha = 0.5f
        } else {
            text_view_ok_compatibility.isClickable = true
            text_view_ok_compatibility.alpha = 1f
        }
    }

    private fun moveAnim(moveView: ImageView, startLocation: IntArray, endLocation: IntArray) {
        val initLocation = IntArray(2)
        // 获取传递过来的VIEW的坐标
        moveView.getLocationInWindow(initLocation)
        // 得到要移动的VIEW,并放入对应的容器中
        val moveViewGroup = getMoveViewGroup()
        val mMoveView = getMoveView(moveViewGroup!!, moveView, initLocation)
        val mAnimator1: ObjectAnimator = ObjectAnimator.ofFloat(
            mMoveView,
            "translationY",
            startLocation[1].toFloat(),
            endLocation[1].toFloat()
        )
        val mAnimator2: ObjectAnimator = ObjectAnimator.ofFloat(
            mMoveView,
            "translationX",
            startLocation[0].toFloat(),
            endLocation[0].toFloat()
        )
        val mAnimator3 =
            ObjectAnimator.ofFloat(mMoveView, "alpha", 1f, 0f)
        val translationAnimatorSet = AnimatorSet()
        translationAnimatorSet.playTogether(mAnimator1, mAnimator2, mAnimator3)
        translationAnimatorSet.duration = 1000
        translationAnimatorSet.start()

        mAnimator1.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
                isMove = true
            }

            override fun onAnimationRepeat(animation: Animator) {}
            override fun onAnimationEnd(animation: Animator) {
                moveViewGroup.removeView(mMoveView)
                isMove = false
            }

            override fun onAnimationCancel(animation: Animator) {}
        })
    }

    /**
     * 创建移动的ITEM对应的ViewGroup布局容器
     */
    private fun getMoveViewGroup(): ViewGroup? {
        val moveViewGroup = window.decorView as ViewGroup
        val moveLinearLayout = LinearLayout(this)
        moveLinearLayout.layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        moveViewGroup.addView(moveLinearLayout)
        return moveLinearLayout
    }

    /**
     * 通过canvas复制view的bitmap
     * 再通过bp获取点击的Item的对应View
     *
     * @param view
     * @return
     */
    private fun getView(view: View): ImageView {

        val width = view.measuredWidth
        val height = view.measuredHeight
        val bp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bp)
        view.draw(canvas)
        canvas.save()
        val iv = ImageView(this)
        iv.setImageBitmap(bp)
        return iv
    }

    /**
     * 获取移动的VIEW，放入对应ViewGroup布局容器
     *
     * @param viewGroup
     * @param view
     * @param initLocation
     * @return
     */
    private fun getMoveView(viewGroup: ViewGroup, view: View, initLocation: IntArray): View {
        viewGroup.addView(view)
        val mLayoutParams = LinearLayout.LayoutParams(WRAP_CONTENT1, WRAP_CONTENT1)
        mLayoutParams.leftMargin = initLocation[0]
        mLayoutParams.topMargin = initLocation[1]
        view.layoutParams = mLayoutParams
        return view
    }

    override fun onPause() {
        super.onPause()
//        MyAnimationUtils.pauseRotation()
    }

    override fun onStop() {
        super.onStop()
        MyAnimationUtils.pauseRotation()
    }

    override fun onDestroy() {
        super.onDestroy()
        MyAnimationUtils.stopRotation()
    }

    override fun onRestart() {
        super.onRestart()
        MyAnimationUtils.resumeRotation()
    }
}